import { uploadUsingPost } from '@/services/pikimbi/fileController';
import { getPictureMessageUsingPost } from '@/services/pikimbi/pictureController';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Alert, Button, Card, Col, Form, message, Row, Space, Spin, Upload } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import React, { useState } from 'react';
import { request } from './../../app.tsx';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const AddPicture: React.FC = () => {
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [picture, setPicture] = useState<API.PictureVO>();
  const [currentFileName, setCurrentFileName] = useState<String>('');
  const [imageUrl, setImageUrl] = useState<string>();
  const [fileList, setFileList] = useState<FileType[]>([]);
  const { baseURL } = request;
  const { baseUploadPath } = request;

  const beforeUpload = (file: FileType) => {
    const isJpgOrPng =
      file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG/JPEG 文件!');
      return Upload.LIST_IGNORE;
    }
    const isLt2M = file.size / 1024 / 1024 < 4;
    if (!isLt2M) {
      message.error('图片必须小于 4MB!');
      return Upload.LIST_IGNORE;
    }
    return true;
  };

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList, file }) => {
    // 只有在上传完成时才执行 upload 函数
    if (file.status === 'done') {
      upload(newFileList);
    }
    setFileList(newFileList);
  };

  const upload = async (newFileList: any) => {
    // 文件上传
    try {
      const uploadRes = await uploadUsingPost({}, newFileList[0].originFileObj, {});
      if (!uploadRes?.data) {
        message.error(uploadRes.message || '上传失败');
        return;
      } else {
        setCurrentFileName(uploadRes.data);
        setImageUrl(baseURL + '/api/' + baseUploadPath + uploadRes.data);
        message.success('上传成功');
      }
    } catch (e: any) {
      message.error('处理失败：' + e.message);
    } finally {
      setSubmitting(false);
    }
  };

  const onRemove = () => {
    setImageUrl(undefined);
    setFileList([]);
    setPicture(undefined);
  };

  const onFinish = async (values: any) => {
    if (submitting || !fileList.length) {
      message.error('请先上传图片');
      return;
    }

    setSubmitting(true);
    setPicture(undefined);
    try {
      // 图片分析
      const params = {
        ...values,
        file: undefined,
        fileName: currentFileName,
      };
      const analysisRes = await getPictureMessageUsingPost(
        params,
        {},
        values.file.file.originFileObj,
      );

      if (analysisRes?.data) {
        setPicture(analysisRes.data);
        message.success('分析成功');
      } else {
        message.error(analysisRes?.message || '分析失败');
      }
    } catch (e: any) {
      message.error('处理失败：' + e.message);
    } finally {
      setSubmitting(false);
    }
  };

  const uploadButton = (
    <div>
      {submitting ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>点击上传</div>
    </div>
  );

  //设置回车自动提交
  const [form] = Form.useForm();
  const handleTextAreaKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault(); // 阻止默认换行行为
      form.submit(); // 手动触发表单提交
    }
  };

  return (
    <div className="add-picture">
      <Row gutter={24}>
        <Col span={12}>
          <Card title="智能分析">
            <Form
              name="addPicture"
              labelAlign="left"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 16 }}
              onFinish={onFinish}
              initialValues={{}}
              form={form}
            >
              <Alert message="仅支持上传JPG/PNG/JPEG文件" banner />
              <div className={'margin-bottom-30'} />
              <Form.Item
                name="file"
                label="上传图片"
                rules={[{ required: true, message: '请上传分析图片！' }]}
              >
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  beforeUpload={beforeUpload}
                  onChange={handleChange}
                  onRemove={onRemove}
                  maxCount={1}
                  fileList={fileList}
                >
                  {imageUrl ? (
                    <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </Form.Item>
              <div className={'margin-bottom-30'} />
              <Form.Item
                name="goal"
                label="分析目标"
                rules={[{ required: true, message: '请输入分析目标！' }]}
              >
                <TextArea
                  placeholder="请输入你的分析需求，例如：解析图片内容"
                  onKeyDown={handleTextAreaKeyDown}
                />
              </Form.Item>

              <Form.Item wrapperCol={{ span: 16, offset: 4 }}>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={submitting}
                    disabled={submitting}
                  >
                    提交
                  </Button>
                  <Button htmlType="reset" onClick={onRemove}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        <Col span={12}>
          <Card title="分析结论">
            {picture?.pictureMessage}
            <Spin spinning={submitting} />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default AddPicture;
